package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.IDialect;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    UserService userService;
    @Autowired
    AddressBookService addressBookService;
    @Autowired
    ShoppingCartService shoppingCartService;

    @Override
    @Transactional
    public void submit(Orders orders) {
        //获取用户ID
        Long userId = BaseContext.getCurrentId();
        //总金额
        BigDecimal total = new BigDecimal(0);
        //生成订单号
        long id = IdWorker.getId();
        //查询用户名
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getId, userId);
        User user = userService.getOne(queryWrapper);
        //获取地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        //通过用户ID获取订单详情
        LambdaQueryWrapper<ShoppingCart> wrapper = Wrappers.lambdaQuery(ShoppingCart.class)
                .eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        OrdersDto ordersDto = new OrdersDto();
        List<OrderDetail> orderDetails = ordersDto.getOrderDetails();
        //遍历购物车商品
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetails.add(orderDetail);
            total = total.add(cart.getAmount());
        }

        //订单号
        orders.setId(id);
        //订单状态
        orders.setStatus(2);
        //下单用户ID
        orders.setUserId(userId);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //结账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //实收金额
        orders.setAmount(total);
        //用户名
        orders.setUserName(user.getName());
        //手机号
        orders.setPhone(user.getPhone());
        //地址
        orders.setAddress(addressBook.getDetail());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        this.save(orders);
        orderDetailService.saveBatch(orderDetails);
        //清空购物车
        shoppingCartService.remove(wrapper);
    }

    @Override
    public Page<OrdersDto> userPage(Integer page, Integer pageSize) {
        Page<Orders> pageInfo1 = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = Wrappers.lambdaQuery(Orders.class)
                .eq(Orders::getUserId, BaseContext.getCurrentId())
                .orderByDesc(Orders::getOrderTime);

        this.page(pageInfo1, queryWrapper);
        Page<OrdersDto> pageInfo2 = new Page<>(page, pageSize);
        BeanUtils.copyProperties(pageInfo1, pageInfo2, "records");

        List<Orders> ordersList = pageInfo1.getRecords();
        List<OrdersDto> ordersDtos = ordersList.stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            LambdaQueryWrapper<OrderDetail> wrapper = Wrappers.lambdaQuery(OrderDetail.class)
                    .eq(OrderDetail::getOrderId, item.getId());
            List<OrderDetail> list = orderDetailService.list(wrapper);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        pageInfo2.setRecords(ordersDtos);
        return pageInfo2;
    }
}
